import Taro, {useDidShow, useReachBottom, useReady} from '@tarojs/taro'
import {useCallback, useEffect, useState} from 'react'
import {SightInfo, SightInfoRet, UserInfo} from '@/type'
import config from '@/config'
import QQMapWX from '@/assets/lib/qqmap-wx-jssdk'
/**
 * 获取用户信息
 */
export const useUserInfo = () => {
  function getUserInfo () {
    return new Promise(resolve => {
      Taro.getUserProfile({
        desc: '完善用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
          let userInfo = Taro.getStorageSync('userInfo')
          Object.assign(userInfo, {
            avatarUrl: 'https://thirdqq.qlogo.cn/g?b=qq&nk=2064825358&s=100'
          }, res.userInfo)
          resolve(res.userInfo)
        }
      })
    })
  }

  return {
    getUserInfo
  }
}

/**
 * 登录校验
 */
export const useCheckLogin = () => {
  const [userInfo, setUserInfo] = useState<UserInfo>({
    avatarUrl: '',
    city: '',
    nickName: ''
  })

  const [isLogin, setLogin] = useState(false)

  const [lock, setLock] = useState(false)

  useReady(() => {
    let token = Taro.getStorageSync('token')
    if (!token) {
      setLock(true)
      Taro.navigateTo({
        url: '/pages/User/Login/index',
      })
      return
    }
    setLogin(true)
    setUserInfo(Taro.getStorageSync('userInfo'))
  })

  useDidShow(() => {
    if (isLogin) {
      return
    }
    let login = Taro.getStorageSync('isLogin')
    if (!login && lock) {
      Taro.navigateTo({
        url: '/pages/User/Login/index',
      })
    }
    setLogin(login)
    if (!userInfo.avatarUrl) {
      setUserInfo(Taro.getStorageSync('userInfo'))
    }
  })

  return {
    isLogin,
    userInfo
  }
}

/**
 * 值防抖
 * @param value
 * @param delay
 */
export const useDebounce = <T>(value: T, delay: number = 500) => {
  const [debounce, setDebounce] = useState<T>(value)
  useEffect(() => {
    const timer = setTimeout(setDebounce, delay, value)
    return () => {
      clearTimeout(timer)
    }
  }, [value, delay])
  return debounce
}

// export const useThrottle = <T>(value: T, delay: number = 500) => {
//   const [throttle, setThrottle] = useState<T>(value)
//   useEffect(() => {
//     let time = new Date()
//
//   }, [value, delay])
// }

/**
 * 分页加载
 * @param getData 请求函数
 * @param size 一次请求的数据
 * @param isLogin 是否登录
 */
export const useSightLoading = (getData: (page: number) => Promise<SightInfoRet>, size: number, isLogin: boolean = true) => {
  const [sightInfos, setSightInfos] = useState<SightInfo[]>([])
  const [page, setPage] = useState(0)
  const [total, setTotal] = useState(0)
  const [more, setMore] = useState(true)

  useEffect(() => {
    if (!isLogin) return
    getData(page).then((res: SightInfoRet) => {
      if (!Array.isArray(res.records)) {
          setMore(false)
          return
      }
      setSightInfos((preSightInfos) => preSightInfos.concat(res.records))
      if (res.total === 0) {
        setMore(false)
      }
      setTotal(res.total)
    })
    // eslint-disable-next-line
  }, [page, size, isLogin])

  useReachBottom(() => {
    if (page < total) {
      setPage(prePage => prePage + 1)
      setMore(true)
    } else {
      setMore(false)
    }
  })

  return {
    sightInfos, more
  }
}

// let key = 'N6VBZ-XPIKU-AKTVZ-2HICQ-B6T4H-TPFQE'  //使用在腾讯位置服务申请的key
// let referer = 'yoto'   //调用插件的小程序的名称
// let startPoint = JSON.stringify({  //起点
//   'name': '中国技术交易大厦',
//   'latitude': 39.984154,
//   'longitude': 116.30749
// });
// let endPoint = JSON.stringify({  //终点
//   'name': '北京西站',
//   'latitude': 39.894806,
//   'longitude': 116.321592
// })
// Taro.navigateTo({
//   url: 'plugin://routePlan/route-plan?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
// })

const QQMapSDK = new QQMapWX({
  key: config.qqMapKey || ''
})

export const useRoutePlan = () => {
  function routeScrollTo (endPoint: {
    name: string
    latitude: number
    longitude: number
  } | string, key: string = 'yoto') {

    endPoint || (endPoint = JSON.stringify({  //终点
      name: '北京西站',
      latitude: 39.894806,
      longitude: 116.321592
    }))
    if (typeof endPoint === 'object') {
      endPoint = JSON.stringify(endPoint)
    }
    Taro.navigateTo({
      url: 'plugin://routePlan/route-plan?key=' + config.key + '&referer=' + key + '&endPoint=' + endPoint
    })
  }

  function geocoder (address: string, region?: string) {
    return new Promise(resolve => {
      let options: {address: string, region?: string} = {address}
      if (region) options.region = region
      QQMapSDK.geocoder({
        ...options,
        success: res => {
          resolve(res.result)
        }
      })
    })
  }


  return {
    routeScrollTo, geocoder
  }
}

/**
 * 维护提示
 */
export const useMaintain = () => {
  const onMaintain = useCallback(() => {
    Taro.hideLoading()
    Taro.showToast({
      title: '正在维护中~~~',
      icon: 'none',
      duration: 500
    })
  }, [])

  return {
    onMaintain
  }
}
